﻿#建议保存编码为：bom头 + utf8

param
(
	[string]$被写入的log内容 = ''
)

${script:k4t_log文件路径} = "/etc/kasini3000/k4t_client/k4t_log.txt"
$随机延时1次数 = 3
$随机延时2次数 = 2


#region 函数
function 随机延时1
{
	$毫秒1 = 170,170,170,230,230,280,280,310,390,450,560,590
	$延时1 = Get-Random -InputObject $毫秒1
	Write-Verbose "延时 $延时1"
	Start-Sleep -Milliseconds $延时1
}

function 随机延时2
{
	$毫秒2 = 710,710,710,820,820,930,930,1040,1150,1260,1370,1580
	$延时2 = Get-Random -InputObject $毫秒2
	Write-Verbose "延时 $延时2"
	Start-Sleep -Milliseconds $延时2
}

function 写入输出txt ($要上锁的文件,$输出值2)
{
	try
	{
		$文件流 = New-Object System.IO.FileStream($要上锁的文件,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Write,[System.IO.FileShare]::Write)  #《-----这句是关键
		$文件流.Position = $文件流.Length #移动光标到文件末尾，以便追加数据。
		$文件 = New-Object System.IO.StreamWriter($文件流,[System.Text.Encoding]::UTF8)
		$文件.WriteLine($输出值2)
		#这里不能加Start-Sleep
		$文件.Dispose()
		$文件流.Dispose()
		return $true
		#问：这个脚本谁写的？有问题找谁技术支持？
		#答：QQ群号=183173532
		#名称=powershell交流群
		# 2016-12-20 转载留名
	}
	catch
	{
		Write-Verbose '文件上锁失败，无法写入！'
		return $false
	}
}

function 循环写入log文件
{
	for ($i1 = $随机延时1次数; $i1 -gt 0; $i1--)
	{
		if ((写入输出txt -要上锁的文件 ${script:k4t_log文件路径}  -输出值2 ${script:被写入的log内容2}) -eq $true)
		{
			Write-Verbose '文件写入成功！'
			exit 0
		}
		随机延时1
	}
}

#endregion 函数

#---main1---
if (Test-Path -LiteralPath '/usr/bin/7za')
{
	$private:有7z = $true
}
else
{
	if (Test-Path -LiteralPath '/etc/kasini3000/node_script/bkj_install_linuxpackage.ps1')
	{
		& '/etc/kasini3000/node_script/bkj_install_linuxpackage.ps1' -被安装的一组包 'p7zip','p7zip-full'
	}
}

if (Test-Path ${script:k4t_log文件路径})
{

	if ( ((Get-Item -LiteralPath ${script:k4t_log文件路径}).length -gt 64mb) -and ($private:有7z -eq $true) )
	{
		Rename-Item -LiteralPath ${script:k4t_log文件路径} -NewName 'k4t_log_bak.txt'
		$时间2 = Get-Date -Format 'yyyy_MM_dd_HH_mm'
		$7zcmd = "/usr/bin/7za a -r -tzip ./${时间2}.zip  /etc/kasini3000/k4t_client/k4t_log_bak.txt"
		Invoke-Expression -Command $7zcmd
		Start-Sleep -Seconds 1
		Remove-Item -Force -LiteralPath '/etc/kasini3000/k4t_client/k4t_log_bak.txt'
		[string]$private:temp01 = /usr/bin/cat /etc/*-release
		Set-Content -LiteralPath ${script:k4t_log文件路径} -Encoding utf8bom -Value $private:temp01
		Add-Content -LiteralPath ${script:k4t_log文件路径} -Encoding utf8bom -Value (/usr/bin/uname -a)
	}
}
else
{
	[string]$private:temp01 = /usr/bin/cat /etc/*-release
	Set-Content -LiteralPath ${script:k4t_log文件路径} -Encoding utf8bom -Value $private:temp01
	Add-Content -LiteralPath ${script:k4t_log文件路径} -Encoding utf8bom -Value (/usr/bin/uname -a)
}

#---main2---
$private:时间 = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
${script:被写入的log内容2} = "$private:时间	$被写入的log内容"
for ($i2 = $随机延时2次数; $i2 -gt 0; $i2--)
{
	循环写入log文件
	随机延时2
}
Write-Error '错误：文件上锁失败无法写入！'
exit 998
